package com.bawei.login.view

import android.view.View
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.common.mvi.BaseMviActivity
import com.bawei.base.RoutePath
import com.bawei.login.R
import com.bawei.login.databinding.ActivityLoginBinding
import com.bawei.login.entity.LoginValues
import com.bawei.login.intent.LoginViewIntent
import com.bawei.login.state.LoginUiState
import com.bawei.login.vm.LoginViewModel
import com.tencent.mmkv.MMKV
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@Route(path = RoutePath.PATH_LOGIN_PAGE)
@AndroidEntryPoint
class LoginActivity : BaseMviActivity<ActivityLoginBinding>() {

    private val mViewModel: LoginViewModel by viewModels()

    override fun getLayoutId(): Int = R.layout.activity_login

    override fun initViews() {
        //获取记住的账号和密码
        var preAccount = MMKV.defaultMMKV().decodeString("pre_account", "")
        var prePwd = MMKV.defaultMMKV().decodeString("pre_pwd","")
        if (!preAccount.isNullOrEmpty() && !prePwd.isNullOrEmpty()){
            mDataBinding.includeLogin.cbRememberPwd.isChecked = true
            mDataBinding.includeLogin.edtLoginName.setText(preAccount)
            mDataBinding.includeLogin.edtLoginPwd.setText(prePwd)
        }

        //注册账号按钮点击事件
        mDataBinding.includeLogin.tvRegister.setOnClickListener {
            mDataBinding.cltLoginCard.visibility = View.INVISIBLE
            mDataBinding.cltRegisterCard.visibility = View.VISIBLE
            mDataBinding.llUserAgreement.visibility = View.INVISIBLE
        }


        //登录按钮点击事件
        mDataBinding.includeLogin.btnLogin.setOnClickListener {
            var uName = mDataBinding.includeLogin.edtLoginName.text.toString().trim()
            var uPwd = mDataBinding.includeLogin.edtLoginPwd.text.toString().trim()
            if (!mDataBinding.cbAgree.isChecked){
                showToastMsg("请先同意用户协议")
            }else{
              loginToServer(uName, uPwd)
            }
        }

        //注册按钮点击事件
        mDataBinding.includeRegister.btnRegister.setOnClickListener {
            var uName = mDataBinding.includeRegister.edtRegisterName.text.toString().trim()
            var uPwd = mDataBinding.includeRegister.edtRegisterPwd.text.toString().trim()
            var uRePwd = mDataBinding.includeRegister.edtRegisteRePwd.text.toString().trim()
            if (!uName.isNullOrEmpty() && !uPwd.isNullOrEmpty() && !uRePwd.isNullOrEmpty() && uPwd == uRePwd){
                registerToServer(uName, uPwd)
            }
        }

    }

    override suspend fun collectUiState() {
        mViewModel.uiState.collect{
            when(it){
                is LoginUiState.LoginSuccess -> handLoginSuccess(it.data)
                is LoginUiState.RegisterSuccess -> handRegisterSuccess(it.data)
                is LoginUiState.LoginFail -> showToastMsg(it.msg)
                is LoginUiState.RegisterFail -> showToastMsg(it.msg)
                else -> {}
            }
        }
    }

    private fun registerToServer(uName: String, uPwd: String){
        lifecycleScope.launch {
            mViewModel.channel.send(LoginViewIntent.RegisterToServer(uName, uPwd))
        }
    }

    private fun loginToServer(uName: String, uPwd: String){
        lifecycleScope.launch {
            mViewModel.channel.send(LoginViewIntent.LoginToServer(uName, uPwd))
        }
    }

    /**
     * 注册成功
     */
    private fun handRegisterSuccess(data: Any) {
        var entity = data as LoginValues
        //回显新账号和密码
        mDataBinding.includeLogin.edtLoginName.setText(entity.uName)
        mDataBinding.includeLogin.edtLoginPwd.setText(entity.uPwd)
        //提示登录
        showToastMsg("注册成功!")
        //切换到登录界面
        mDataBinding.cltLoginCard.visibility = View.VISIBLE
        mDataBinding.cltRegisterCard.visibility = View.INVISIBLE
        mDataBinding.llUserAgreement.visibility = View.VISIBLE
    }

    /**
     * 登录成功
     */
    private fun handLoginSuccess(data: Any) {
        var entity = data as LoginValues
        //是否需要记住密码
        if (mDataBinding.includeLogin.cbRememberPwd.isChecked){
            MMKV.defaultMMKV().encode("pre_account", entity.uName)
            MMKV.defaultMMKV().encode("pre_pwd", entity.uPwd)
        }

        //跳转到主页面
        ARouter.getInstance().build(RoutePath.PATH_MAIN_PAGE).navigation()
        this@LoginActivity.finish()
    }




}